%%%-------------------------------------------------------------------
%% @doc okmqtt public API
%% @end
%%%-------------------------------------------------------------------

-module(okmqtt_app).
-behaviour(application).

-define(SSL_PORT, 18831).
-define(WS_PORT, 18883).

%% Application callbacks
-export([start/2, stop/1]).

start(_StartType, _StartArgs) ->
  create_system_table(),
  Pid=okmqtt_sup:start_link(),
  config(),
  lager:start(),
  start_server(),
  %%start_web(),
  Pid.

stop(_State) -> mnesia:stop(), ok.
config() ->
  io:setopts({encoding, unicode}),
  application:set_env(mnesia, dir, "data"),
  ok.
start_server() ->
  {_, Config} = application:get_env(server),
  log:log("config ~p", [Config]),
  {ip, Ip} = lists:keyfind(ip, 1, Config),
  {ssl, SSL} = lists:keyfind(ssl, 1, Config),
  {port, Port} = lists:keyfind(port, 1, Config),
  case SSL of
    false -> start_tcp(Port, Ip);
    undefined -> start_tcp(Port, Ip);
    true ->
      {cafile, CA} = lists:keyfind(cafile, 1, Config),
      {cert, Cert} = lists:keyfind(cert, 1, Config),
      {key, Key} = lists:keyfind(key, 1, Config),
      start_ssl(Port, Ip, CA, Cert, Key)
  end.

start_tcp(Port, Ip) ->
  {ok, _} = ranch:start_listener(mqtt_server, 100, ranch_tcp,
    [{port, Port}, {ip, Ip},{max_connections,102400}], mqtt_process, []).

start_ssl(Port, Ip, CA, Cert, Key) ->
  {ok, _} = ranch:start_listener(mqtt_server, 100, ranch_ssl,
    [{port, Port}, {ip, Ip},{max_connections,102400}, {cacertfile, CA},
      {certfile, Cert}, {keyfile, Key}], mqtt_process, []).

start_web() ->
  Dispatch = cowboy_router:compile([
    {'_', [
      {"/mqtt", mqtt_websocket, []},
      {"/websocket", websocket_handler, []}
    ]}
  ]),

  {ok, _} = cowboy:start_clear(http, [{port, ?WS_PORT}], #{env => #{dispatch => Dispatch}}).
create_system_table() ->
  mnesia:stop(),
  %%创建数据库结构
  mnesia:create_schema([node()]),
  mnesia:start(),
  subscribe_server:cre_tab(),
  retain_server:cre_tab(),
  cache_server:cre_tab(),
  session_server:cre_tab().

